package com.prs.crm.action.sys;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.XJAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;

import com.prs.crm.domain.sys.Form;
import com.prs.crm.domain.sys.FormField;
import com.prs.crm.exception.InValidDeleteException;
import com.prs.crm.service.sys.FormService;

public class FormAction extends XJAction {

	private static final long serialVersionUID = 3878978960776455327L;

	private FormService formService;

	private Form form;

	private FormField field;

	private PaginationSupport pagination;

	private Integer[] formIds;

	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public FormService getFormService() {
		return formService;
	}

	public void setForm(Form form) {
		this.form = form;
	}

	public Form getForm() {
		return form;
	}

	public void setField(FormField field) {
		this.field = field;
	}

	public FormField getField() {
		return field;
	}

	public void setFormIds(Integer[] formIds) {
		this.formIds = formIds;
	}

	public Integer[] getFormIds() {
		return formIds;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	@Action("listForm")
	public String execute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Form.class);
		this.setPagination(this.getFormService().listByPage(criteria,
				getPaginationHelper().prepare(pagination)));
		return SUCCESS;
	}

	@Action("editForm")
	public String edit() {
		return SUCCESS;
	}

	@Action(value = "saveForm", results = {
			@Result(name = "success", type = "redirect", location = "listForm"),
			@Result(name = "error", type = "chain", location = "editForm") })
	public String save() {
		if (form.getName() == null || "".equals(form.getName().trim())) {
			addActionError("名称不能为空");
			return ERROR;
		}
		if (form.getEname() == null || "".equals(form.getEname().trim())) {
			addActionError("英文名称不能为空");
			return ERROR;
		}
		if (form.getClassName() == null
				|| "".equals(form.getClassName().trim())) {
			addActionError("模型映射不能为空");
			return ERROR;
		}
		this.getFormService().save(form);
		return SUCCESS;
	}

	@Action(value = "removeForm", results = {
			@Result(name = "success", type = "redirect", location = "listForm"),
			@Result(name = "error", type = "chain", location = "listForm") })
	public String remove() {
		try {
			if (formIds == null) {
				this.addActionError("请选择要删除的客户");
				return ERROR;
			}
			this.getFormService().batchRemove(formIds);
			return SUCCESS;
		} catch (InValidDeleteException e) {
			// TODO: handle exception
			this.addActionError("该客户已被引用，不能删除");
			return ERROR;
		}
	}
}
